package py.progweb.sgc.gui.client.widget;

import java.util.ArrayList;
import java.util.List;

import py.progweb.sgc.gui.shared.dialogmodel.DataRecord;

import com.google.gwt.user.client.Window;
import com.smartgwt.client.data.DataSource;
import com.smartgwt.client.data.fields.DataSourceTextField;
import com.smartgwt.client.types.SelectionStyle;
import com.smartgwt.client.widgets.grid.ListGrid;
import com.smartgwt.client.widgets.grid.ListGridField;
import com.smartgwt.client.widgets.grid.ListGridRecord;

/**
 * Tabla con campos de filtrado
 * @author jtalavera
 *
 */
public class TablaFiltro extends ListGrid {
	
	List<DataRecord> datos;
	DescCampo [] campos;
	ListGrid grid;

	public TablaFiltro(List<DataRecord> datos, DescCampo ... campos) {
		super();
		
		this.grid = this;
		this.datos = datos;
		this.campos = campos;
		
		this.setWidth100();
		this.setHeight100();
		
		ListGridField [] fields = new ListGridField[campos.length];
		DataSource ds = new DataSource();
		ds.setClientOnly(true);				
	
		int i = 0;		
		for (DescCampo d : campos) {
			fields[i++] = new ListGridField(d.getNombre(), d.getDescripcion());

			DataSourceTextField dsf = new DataSourceTextField();
			dsf.setName(d.getNombre());
			
			if ("idgruporegla".equals(d.getNombre()))
				dsf.setPrimaryKey(true);
			
			ds.addField(dsf);		
		}
		
		this.grid.setFields(fields);
		
		
		ListGridRecord [] records = new ListGridRecord[datos.size()];
		i = 0;
		for (DataRecord dr: datos) {
			ListGridRecord r = new ListGridRecord();
			
			for(String atributo : dr.getAtributos()) 
				r.setAttribute(atributo, dr.getAtributo(atributo).toString());				
			
			r.setAttribute("_dataRecord", dr);
			
			records[i++] = r;
			ds.addData(r);
		}
		
		//this.grid.setData(records);
		this.grid.setDataSource(ds);
		this.grid.setAutoFetchData(true);
		this.grid.setShowFilterEditor(true);	
		this.grid.setSelectionType(SelectionStyle.MULTIPLE);
	}
	
	public List<DataRecord> getFilasSeleccionadas() {
		ListGridRecord [] records = this.grid.getSelection();
		ArrayList<DataRecord> result = new ArrayList<DataRecord>();
		
		for(ListGridRecord r : records){ 
			result.add((DataRecord)r.getAttributeAsObject("_dataRecord"));
		}
		return result;
	}
}
